package com.cjh.wechat.core.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.cjh.wechat.commom.util.ObjectSer;
import com.cjh.wechat.commom.vo.ReceiveMessVo;
import com.cjh.wechat.core.service.RedisService;
import com.cjh.wechat.core.service.UnReadService;
import com.cjh.wechat.core.service.UserService;
import redis.clients.jedis.Jedis;

@Service
public class UnReadRecordService implements UnReadService
{
    private static final String UNREAD_RECORD = "unread";
    @Resource
    private RedisService        redisService;
    @Resource
    private UserService         userService;
    
    @Override
    public List<ReceiveMessVo> getUnReadRecord(String id)
    {
        try (Jedis jedis = redisService.get())
        {
            Set<byte[]> set = jedis.zrange((UNREAD_RECORD + "_" + id).getBytes(), 0, -1);
            Iterator<byte[]> iter = set.iterator();
            List<ReceiveMessVo> list = new ArrayList<ReceiveMessVo>();
            while (iter.hasNext())
            {
                ReceiveMessVo receiveMessVo = (ReceiveMessVo) ObjectSer.ByteToObject(iter.next());
                list.add(receiveMessVo);
            }
            return list;
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return new ArrayList<ReceiveMessVo>();
    }
    
    @Override
    public void addUnReadRecord(String id, String dateTime, ReceiveMessVo receiveMessVo)
    {
        try (Jedis jedis = redisService.get())
        {
            jedis.zadd((UNREAD_RECORD + "_" + id).getBytes(), //
                    Double.parseDouble(dateTime), ObjectSer.ObjectToByte(receiveMessVo));
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
    
    @Override
    public void removeUnReadRecord(String id, ReceiveMessVo receiveMessVo)
    {
        try (Jedis jedis = redisService.get())
        {
            jedis.zrem((UNREAD_RECORD + "_" + id).getBytes(), ObjectSer.ObjectToByte(receiveMessVo));
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}
